package com.example.cash_register.controller;


import com.example.cash_register.model.order.Order;
import com.example.cash_register.model.order.OrderDetail;
import com.example.cash_register.model.product.Product;
import com.example.cash_register.model.product.ProductParam;
import com.example.cash_register.model.user.PasswordValidator;
import com.example.cash_register.model.user.User;
import com.example.cash_register.model.user.UsernameValidator;
import com.example.cash_register.service.OrderService;
import com.example.cash_register.service.ProductService;
import com.example.cash_register.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Controller
public class DoController {
    private final UserService userService;
    private final UsernameValidator usernameValidator;
    private final PasswordValidator passwordValidator;
    private final ProductService productService;
    private final OrderService orderService;

    @Autowired
    public DoController(UserService userService,UsernameValidator usernameValidator,PasswordValidator passwordValidator,ProductService productService,OrderService orderService) {
        this.userService = userService;
        this.usernameValidator = usernameValidator;
        this.passwordValidator = passwordValidator;
        this.productService = productService;
        this.orderService = orderService;
    }

    @PostMapping("/register.do")
    public String register(String username, String password, HttpServletRequest request) {
        String module = "用户注册";
        String redirectUrl = "/static/register.html";

        log.debug("{}: username = {}, password = {}", module, username, password);

        username = usernameValidator.validate(module,redirectUrl,username);
        password = passwordValidator.validate(module,redirectUrl,password);

        try {
            User user = userService.register(username,password);

            HttpSession session = request.getSession();
            session.setAttribute("currentUser",user);

            log.debug("{}: 注册成功,user = {}",module,user);
            return "redirect:/";
        }catch (DuplicateKeyException e) {
            throw new ErrRedirectException("username 重复",module,redirectUrl,e);
        }
    }

    @PostMapping("/login.do")
    public String login(String username,String password,HttpServletRequest request) {
        String module = "用户登录";
        String redirectUrl = "/static/login.html";
        log.debug("{}: username = {},password = {}",module,username,password);
        username = usernameValidator.validate(module,redirectUrl,username);
        password = passwordValidator.validate(module,redirectUrl,password);

        User user = userService.login(username,password);
        if (user == null) {
            throw new ErrRedirectException("username or password error",module,redirectUrl);
        }
        HttpSession session = request.getSession();;
        session.setAttribute("currentUser",user);

        log.debug("{}: 登陆成功, user = {}",module,user);
        return "redirect:/";
    }

    @PostMapping("/product/create.do")
    public String productCreate(ProductParam param,HttpServletRequest request) {
        String module = "用户登录";
        String redirectUrl = "/product/create.html";
        log.debug("{}: 请求参数 = {} ",module,param);

        User currentUser = null;
        HttpSession session = request.getSession(false);
        if(session != null) {
            currentUser = (User) session.getAttribute("currentUser");
        }

        if(currentUser == null) {
            log.debug("{}: 用户未登录!",module);
            return "redirect:/login.html";
        }
        log.debug("{}: 当前登录用户为: {}",module,currentUser);
        Product product = productService.create(currentUser,param);
        return "redirect:/product/list.html";
    }

    @PostMapping("/product/update.do")
    public String productUpdate(ProductParam productParam,HttpServletRequest request) {
        log.debug("商品更新 请求参数 = {}",productParam);
        User currentUser = null;
        HttpSession session = request.getSession(false);
        if(session != null) {
            currentUser = (User) session.getAttribute("currentUser");
        }
        if(currentUser == null) {
            log.debug("商品更新，用户未登录");
            return "redirect:/login.html";
        }
        Product product = productService.update(currentUser,productParam);

        log.debug("商品更新成功,product = {}",product);
        return "redirect:/product/list.html";
    }

    @PostMapping("/order/create.do")
    public String orderCreate(@RequestParam("create-param") String createParam,HttpServletRequest request) {
        log.debug("购买商品: createParam = {}", createParam);
        Map<Integer,Integer> toBoughtProductMap = new HashMap<>();

        String[] split = createParam.split(",");
        for (String s : split) {
            String[] group = s.split("-");
            String productIdStr = group[0];     // 参数不对，就会抛异常
            String numberStr = group[1];     // 参数不对，就会抛异常

            int productId = Integer.parseInt(productIdStr);     // 参数不对，就会抛异常
            int number = Integer.parseInt(numberStr);           // 参数不对，就会抛异常


            toBoughtProductMap.put(productId,number);
        }

        log.debug("toBoughtProductMap = {}",toBoughtProductMap);
        User currentUser = null;
        HttpSession session = request.getSession(false);
        if(session != null) {
            currentUser = (User)session.getAttribute("currentUser");
        }
        if (currentUser == null) {
            log.debug("购买商品，用户未登录");
            return "redirect:/login.html";
        }
        log.debug("当前用户: user = {}",currentUser);
        Order order = orderService.create(currentUser,toBoughtProductMap);
        log.debug("创建订单: {}",order);
        return "redirect:/order/detail/" +order.getUuid();
    }

    @GetMapping("/order/detail/{uuid}")
    public String orderDetail(@PathVariable("uuid") String uuid, HttpServletRequest request, Model model) {
        log.debug("订单详情: orderId = {}",uuid);

        User currentUser = null;
        HttpSession session = request.getSession(false);
        if(session != null) {
            currentUser = (User)session.getAttribute("currentUser");
        }
        if (currentUser == null) {
            log.debug("订单详情，用户未登录");
            return "redirect:/login.html";
        }
        log.debug("当前用户: user = {}", currentUser);
        OrderDetail orderDetail = orderService.query(uuid);
        log.debug("order = {}",orderDetail);
        model.addAttribute("order",orderDetail);
        return "order-detail";
    }

    @GetMapping("/order/confirm/{orderId}")
    public String orderConfirm(@PathVariable int orderId,HttpServletRequest request) {
        log.debug("确认订单: orderId = {}",orderId);
        User currentUser = null;
        HttpSession session = request.getSession(false);
        if (session != null) {
            currentUser = (User) session.getAttribute("currentUser");
        }
        if (currentUser == null) {
            log.debug("商品更新: 用户未登录，无权进行该操作");
            return "redirect:/login.html";
        }
        log.debug("当前用户: user = {}", currentUser);

        orderService.confirm(orderId);
        return "redirect:/order/list.html";
    }

    @GetMapping("/order/cancel/{orderId}")
    public String orderCancel(@PathVariable int orderId,HttpServletRequest request) {
        log.debug("确认订单: orderId = {}", orderId);

        User currentUser = null;
        HttpSession session = request.getSession(false);
        if (session != null) {
            currentUser = (User) session.getAttribute("currentUser");
        }
        if (currentUser == null) {
            log.debug("商品更新: 用户未登录，无权进行该操作");
            return "redirect:/login.html";
        }
        log.debug("当前用户: user = {}", currentUser);

        orderService.cancel(orderId);

        return "redirect:/order/list.html";
    }
}
